package com.czk.springcloud.lb.impl;

import com.czk.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/12/18 11:31
 */
@Component
@Slf4j
public class MyLoadBalancer implements LoadBalancer {
    /**
     * 定义原子类
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * cas交换，线程安全
     *
     * @return
     */
    public int getAndIncrement() {
        while (true) {
            // 拿到现在的值
            int pre = atomicInteger.get();
            int next;
            if (pre < Integer.MAX_VALUE) {
                next = pre + 1;
            } else {
                next = 0;
            }
            if (atomicInteger.compareAndSet(pre, next)) {
                log.info("next的访问次数=" + next);
                return next;
            }
        }
    }

    /**
     * 实现负载均衡
     *
     * @param serviceInstances
     * @return
     */
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        // 取余数
        int index = this.getAndIncrement() % serviceInstances.size();
        ServiceInstance serviceInstance = serviceInstances.get(index);
        return serviceInstance;
    }
}
